package cn.com.ddapp.ddm.fragment.base.commidcontext;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.bean.DetailsBean;
import cn.com.ddapp.ddm.fragment.base.BaseFragment;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import cn.com.ddapp.ddm.util.WebHelper;

/**
 * Created by Administrator on 2016/8/22 0022.//商品详情页面，图文详情
 */
public class FormatFileFragment extends BaseFragment {
    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.infionView)
    WebView webView;
    @BindView(R.id.img_error_layout)
    ImageView img_error_layout;
    @BindView(R.id.nogoodinfo)
    TextView nogoodinfo;
    private DetailsBean detailsBean;
    String userId;
    @Override
    protected String getFragmentTag() {
        return null;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
         userId= SPUtils.getStringData(getContext(), SPUtils.USERID);
        if(TDevice.isTablet(getContext())){
            toGetData();
            Log.i("aaa","111");
        }else{
            togetProData();
            Log.i("aaa","222");
        }


    }

    private void togetProData() {
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        OkUtilCallback okUtilCallback = new OkUtilCallback(mEmptyLayout) {
            @Override
            public void onMyResponse(String response, int id) {
//                Log.e("TAG", "onMyResponse: " + response);
                detailsBean = gson.fromJson(response, DetailsBean.class);
                if ((!AppConfig.RESULT_OK.equalsIgnoreCase(detailsBean.getResult()))) {
                    nogoodinfo.setVisibility(View.VISIBLE);
                } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(detailsBean.getResult()))) {
                    nogoodinfo.setVisibility(View.GONE);
                    initInProfion();
                }
            }
        };
        Bundle bundle=getArguments();
        String goodsId =  AppConfig.GoodsId;
        if(bundle!=null)
        {
            goodsId = bundle.getString("goodsId");
        }
        OKUtilAPI.get(OKUtilAPI.CommidUrl_1 + "?wid=" + AppConfig.CITY_ID + "&id=" + goodsId + "&userId=" + userId, "", okUtilCallback);
    }

    private void initInProfion() {
        try{
            StringBuffer body = new StringBuffer();
            if(!TextUtils.isEmpty(detailsBean.getDetail().getGoodsDetail().getGoodsInfo())){

                body.append(WebHelper.WEB_STYLE).append(WebHelper.WEB_LOAD_IMAGES);
                body.append(WebHelper.setHtmlCotentSupportImagePreview(detailsBean.getDetail().getGoodsDetail().getGoodsInfo()));

                body.append("<br/>");
                webView.loadDataWithBaseURL(null, detailsBean.getDetail().getGoodsDetail().getGoodsInfo()
                        +"<style>"+
                                "img{max-width:100%;}" +
                        "</style>"
                        ,
                        "text/html", "utf-8", null);
                webView.setInitialScale(100);
                WebSettings settings = webView.getSettings();
                webView.setHorizontalScrollBarEnabled(false);//禁止水平滚动
                webView.setVerticalScrollBarEnabled(true);//允许垂直滚动
                settings.setLoadWithOverviewMode(true);
                settings.setJavaScriptEnabled(true);
                settings.setUseWideViewPort(true);
                settings.setLoadWithOverviewMode(true);
                settings.setJavaScriptCanOpenWindowsAutomatically(true);
                settings.setUseWideViewPort(true);//关键点
                // 设置自适应屏幕，两者合用
                settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                settings.setJavaScriptEnabled(true);
//                settings.setDefaultFontSize(50);
                settings.setTextSize(WebSettings.TextSize.NORMAL);//设置字体大小
                settings.setUseWideViewPort(true);// 将图片调整到适合webview的大小
                settings.setLoadWithOverviewMode(true);
                // 设置可以缩放
//                settings.setSupportZoom(true);
//                settings.setBuiltInZoomControls(true);
                System.out.println("详情显示");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void toGetData() {
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        OkUtilCallback okUtilCallback = new OkUtilCallback(mEmptyLayout) {
            @Override
            public void onMyResponse(String response, int id) {
//                Log.e("TAG", "onMyResponse: " + response);
                detailsBean = gson.fromJson(response, DetailsBean.class);
                 if ((!AppConfig.RESULT_OK.equalsIgnoreCase(detailsBean.getResult()))) {
                     nogoodinfo.setVisibility(View.VISIBLE);
                } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(detailsBean.getResult()))) {
                     nogoodinfo.setVisibility(View.GONE);
                    initInfion();

                }
            }
        };
        Bundle bundle=getArguments();
        String goodsId =  AppConfig.GoodsId;
        if(bundle!=null)
        {
            goodsId = bundle.getString("goodsId");
        }
        OKUtilAPI.get(OKUtilAPI.CommidUrl_1 + "?wid=" + AppConfig.CITY_ID + "&id=" + goodsId+ "&userId=" + userId, "", okUtilCallback);
    }

    private void initInfion() {
        try{
            StringBuffer body = new StringBuffer();
            if(!TextUtils.isEmpty(detailsBean.getDetail().getGoodsDetail().getGoodsInfo())){

                body.append(WebHelper.setHtmlCotentSupportImagePreview(detailsBean.getDetail().getGoodsDetail().getGoodsInfo()));
                body.append(WebHelper.WEB_STYLE).append(WebHelper.WEB_LOAD_IMAGES);

                body.append("<br/>");
                webView.loadDataWithBaseURL(null, detailsBean.getDetail().getGoodsDetail().getGoodsInfo(),
                        "text/html", "utf-8", null);

                WebSettings settings = webView.getSettings();


                // 自适应屏幕
                webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                webView.getSettings().setLoadWithOverviewMode(true);
                webView.setInitialScale(100);
                // 支持javascript
                // 设置可以支持缩放
                webView.getSettings().setSupportZoom(true);
                // 设置出现缩放工具
                webView.getSettings().setBuiltInZoomControls(true);
                webView.getSettings().setDisplayZoomControls(false);
                // 扩大比例的缩放
                webView.getSettings().setUseWideViewPort(false);
                webView.getSettings().setJavaScriptEnabled(true);
                settings.setTextSize(WebSettings.TextSize.LARGER);

            }
        }catch (Exception e){
            e.printStackTrace();
        }



//            settings.setLoadWithOverviewMode(true);
//
//            settings.setJavaScriptEnabled(true); // 支持js
//
//            settings.setUseWideViewPort(false); // 将图片调整到适合webview的大小
//
//            settings.setSupportZoom(true); // 支持缩放
//
//            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // 支持内容重新布局
//
//            settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
//            if (NetUtils.isConnected(getActivity())) {
//                settings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
//            } else {
//                settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //设置 缓存模式
//            }
//            // 开启 DOM storage API 功能
//            settings.setDomStorageEnabled(true);
//            //开启 database storage API 功能
//            settings.setDatabaseEnabled(true);
//            settings.setAppCacheEnabled(true);
//            settings.setTextZoom(100);
//
//            webView.setWebViewClient(new WebViewClient() {
//                @Override
//                public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                    view.loadUrl(url);
//                    return true;
//        }
//    });

    }


    @OnClick({R.id.img_error_layout})
     public void onClick(View view){
         switch (view.getId()){
             case R.id.img_error_layout:
                 initData();
                 break;
         }
     }
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tuwen;
    }

    @Override
    public void onDestroy() {
        if (webView != null) {
            ViewGroup parent = (ViewGroup) webView.getParent();
            if (parent != null) {
                parent.removeView(webView);
            }
            webView.removeAllViews();
            webView.destroy();
        }
        super.onDestroy();
    }
}
